<script lang="ts" setup>
import type { AnalysisOverviewItem } from '@vben/common-ui';
import type { SeriesOption } from '@vben/plugins/echarts';
import type { SysInfo, TabOption } from '@vben/types';

import { onMounted, ref, shallowRef } from 'vue';

import { AnalysisChartsTabs, AnalysisOverview } from '@vben/common-ui';
import {
  SvgBellIcon,
  SvgCakeIcon,
  SvgCardIcon,
  SvgDownloadIcon,
} from '@vben/icons';

import { useAnalyticsStore } from '#/store';

import analyticsFile from './analytics-file.vue';
import analyticsProcess from './analytics-process.vue';
import AnalyticsTrends from './analytics-trends.vue';

const analyticsStore = useAnalyticsStore();
const sysInfo = ref<SysInfo>({});
const recentCpuInfo = ref<{
  series: SeriesOption;
  xdata: string[];
  yAxis: object[];
}>({
  series: {
    areaStyle: {},
    data: [],
    itemStyle: {
      color: '#5ab1ef',
    },
    smooth: true,
    type: 'line',
  },
  xdata: [],
  yAxis: [
    {
      axisLabel: {
        formatter(val: number) {
          return `${val}%`;
        },
      },
      axisTick: {
        show: false,
      },
      max: 100,
      splitArea: {
        show: true,
      },
      splitNumber: 4,
      type: 'value',
    },
  ],
});
const recentMemInfo = ref<{
  series: SeriesOption;
  xdata: string[];
  yAxis: object[];
}>({
  series: {
    areaStyle: {},
    data: [],
    itemStyle: {
      color: '#5ab1ef',
    },
    smooth: true,
    type: 'line',
  },
  xdata: [],
  yAxis: [
    {
      axisLabel: {
        formatter(val: number) {
          return `${val}%`;
        },
      },
      axisTick: {
        show: false,
      },
      max: 100,
      splitArea: {
        show: true,
      },
      splitNumber: 4,
      type: 'value',
    },
  ],
});

const overviewItems = shallowRef<AnalysisOverviewItem[]>([]);

function bytesToGB(bytes: number | undefined, is_number: boolean = false) {
  if (bytes === undefined) return;
  // 将字节转换为GB，1GB = 1024 * 1024 * 1024 字节
  const gb = bytes / (1024 * 1024 * 1024);
  if (is_number) return +gb.toFixed(2);
  // 使用 toFixed 方法保留两位小数
  return `${gb.toFixed(2)} GB`;
}

const setOverviewItems = () => {
  overviewItems.value = [
    {
      icon: SvgCardIcon,
      title: 'CPU空闲率',
      totalTitle: 'CPU利用率',
      suffix: '%',
      value: sysInfo.value.cpuFree,
      totalValue: sysInfo.value.cpuUsed,
      totalSuffix: '%',
      decimals: 2,
    },
    {
      icon: SvgCakeIcon,
      title: '内存可用量',
      totalTitle: '内存总量',
      suffix: 'GB',
      value: Number(bytesToGB(sysInfo.value.memoryFree, true)),
      totalValue: Number(bytesToGB(sysInfo.value.memoryTotal, true)),
      totalSuffix: 'GB',
      decimals: 2,
    },
    {
      icon: SvgDownloadIcon,
      title: '进程总数',
      totalTitle: '系统启动日期',
      value: sysInfo.value.processCount,
      totalPrefix: sysInfo.value.bootDate,
      totalValue: Number.NaN,
    },
    {
      icon: SvgBellIcon,
      title: '更新日期',
      prefix: sysInfo.value.createDate,
      value: Number.NaN,
      totalValue: Number.NaN,
      click: async () => {
        sysInfo.value = await analyticsStore.refreshSysInfo();
        setOverviewItems();
      },
    },
  ];
};

onMounted(async () => {
  sysInfo.value = await analyticsStore.getSysInfo();
  setOverviewItems();

  const data = await analyticsStore.getRecentSysInfo();
  const seriesData: number[] = [];
  const memData: number[] = [];
  const xdata: string[] = [];
  let temp: number | undefined;
  const memTotal = Number(bytesToGB(sysInfo.value.memoryTotal, true));
  data.forEach((value: SysInfo, index: number) => {
    seriesData.push(value.cpuUsed === undefined ? 0 : value.cpuUsed);
    temp = memTotal - Number(bytesToGB(value.memoryFree, true));
    memData.push(
      temp === undefined ? 0 : Number(((temp / memTotal) * 100).toFixed(2)),
    );
    xdata.push(value.createDate === undefined ? `${index}` : value.createDate);
  });
  recentCpuInfo.value.series.data = seriesData.reverse();
  recentCpuInfo.value.xdata = xdata.reverse();

  recentMemInfo.value.series.data = memData.reverse();
  recentMemInfo.value.xdata = xdata.reverse();
});

const chartTabs: TabOption[] = [
  {
    label: 'CPU利用率',
    value: 'trends',
  },
  {
    label: '内存使用率',
    value: 'memTrends',
  },
  // {
  //   label: '月访问量',
  //   value: 'visits',
  // },
];
</script>

<template>
  <div class="p-5">
    <AnalysisOverview :items="overviewItems" />
    <AnalysisChartsTabs :tabs="chartTabs" class="mt-5">
      <template #trends>
        <AnalyticsTrends
          :series="recentCpuInfo.series"
          :xdata="recentCpuInfo.xdata"
          :y-axis="recentCpuInfo.yAxis"
        />
      </template>
      <template #memTrends>
        <AnalyticsTrends
          :series="recentMemInfo.series"
          :xdata="recentMemInfo.xdata"
          :y-axis="recentCpuInfo.yAxis"
        />
      </template>
      <!-- <template #visits>
        <AnalyticsVisits />
      </template> -->
    </AnalysisChartsTabs>

    <analyticsProcess />
    <analyticsFile />
    <!-- <AnalysisChartCard class="mt-5 md:mr-4 md:mt-0 md:w-1/3" title="访问数量">
        <AnalyticsVisitsData />
      </AnalysisChartCard>
      <AnalysisChartCard class="mt-5 md:mr-4 md:mt-0 md:w-1/3" title="访问来源">
        <AnalyticsVisitsSource />
      </AnalysisChartCard>
      <AnalysisChartCard class="mt-5 md:mt-0 md:w-1/3" title="访问来源">
        <AnalyticsVisitsSales />
      </AnalysisChartCard> -->
  </div>
</template>
